<?php
	
	/**
	 * 转帐
	 * @param int $pTransferType;//转账类型 1确认转账 2 取消转账
	 * @param int $deal_id  标的id	 
	 * @param string $ref_data 逗号分割的, 1：投资,填还款日期(int)  ; 2代偿，3代偿还款列表; 4债权转让: id; 5结算担保收益:金额，如果为0,则取fanwe_deal.guarantor_pro_fit_amt ;
	 * @param int $MerCode  商户ID
	 * @param string $cert_md5 
	 * @param string $post_url
	 * @return string
	 */
	function DoLoans($pTransferType, $deal_id, $repay_start_time=0, $platformNo,$post_url,$mchnt_user_id){
		set_time_limit(0);
		$results = array();
		$results['status'] = 1;
		
		$pWebUrl= SITE_DOMAIN.APP_ROOT."/index.php?ctl=collocation&act=response&class_name=".COLLNAME."&class_act=DoLoans&from=".$_REQUEST['from']."&repay_start_time=".$repay_start_time;//web方式返回
		$pS2SUrl= SITE_DOMAIN.APP_ROOT."/index.php?ctl=collocation&act=notify&class_name=".COLLNAME."&class_act=DoLoans&from=".$_REQUEST['from']."&repay_start_time=".$repay_start_time;//s2s方式返回
		
		$deal = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."deal where id = ".$deal_id);
		
		$t_user_id = intval($deal['user_id']);	

		$t_arr = $GLOBALS['db']->getAll("select fcp.*,dorder.money,dorder.deal_id,dorder.user_id,dorder.ecv_id,dorder.interestrate_id from ".DB_PREFIX."fuioupay_cp_transaction as fcp left join ".DB_PREFIX."deal_load as dorder on dorder.pP2PBillNo=fcp.requestNo where fcp.code = '0000' and fcp.tenderId = ".$deal_id." and fcp.is_complete_transaction = 0");

 		if(!$repay_start_time){
 			$repay_start_time=TIME_UTC;
 		}
		
		require_once APP_ROOT_PATH."system/libs/user.php";
		require_once APP_ROOT_PATH.'system/collocation/fuioupay/transferBu.php';

  		foreach($t_arr as $key => $t_r)
		{
			if($pTransferType!=2)	
				$GLOBALS['db']->query("update ".DB_PREFIX."fuioupay_cp_transaction set repay_start_time = '".$repay_start_time."',update_time=".TIME_UTC." where is_callback = 1 and requestNo = ".$t_r["requestNo"]);
			
			$tuser = get_user_info("*","id=".$t_r['user_id']);
			
			$data = $Sign_data= array();
			$requestNo = $t_r["requestNo"]; 
			$data['requestNo'] = $requestNo;//请求流水号
			$data['platformNo'] = $platformNo;// 商户编号
			
			$Sign_data['ver'] = "0.44";
			$Sign_data['contract_no']=$t_r["contract_no"]; 
			$Sign_data['in_cust_no']=$t_r["in_cust_no"]; 
			$Sign_data['mchnt_cd']=$platformNo; 
			$Sign_data['mchnt_txn_ssn']=get_microtime();
			$Sign_data['out_cust_no']=$t_r["out_cust_no"];
			   
			
			if($pTransferType ==1){
				$Sign_data['amt']= $t_r["paymentAmount"]*100;
				$Sign_data['rem']=$t_r["rem"];
			}else{
				$Sign_data['rem']='退款';
			}
			
			ksort($Sign_data);
			
			$Sign_old = '';
			foreach($Sign_data as $k => $v){
				if($k == 'ver'){
					$Sign_old .=$v;
					$Sign_old_a .=$k;
				}else{
					$Sign_old .= $v."|";
					$Sign_old_a .= $k."+|+";
				}
			}
			
			/* 签名数据 */
			$pSign=rsaSign($Sign_old,PRIVATE_KEY_PATH);
			if($pTransferType==1){
				$data['mode'] = "CONFIRM";	
			}else{
				$data['mode'] = "CANCEL";	
			}
			
			/* 请求参数 */  
			$req = http_build_query($Sign_data)."&signature=".urlencode($pSign);

			$fuioupay_log = array();
			$fuioupay_log['code'] = 'bhaController';
			$fuioupay_log['create_date'] = to_date(TIME_UTC,'Y-m-d H:i:s');
			$fuioupay_log['strxml'] = $req;
			$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_log",$fuioupay_log);
			$log_id = $GLOBALS['db']->insert_id();

			/* 调用账户查询服务 */
		//if(!file_exists(APP_ROOT_PATH.'system/collocation/fuioupay/resuls.php')){
			$options = array(
				CURLOPT_POST => TRUE,
				CURLOPT_RETURNTRANSFER => TRUE,
				CURLOPT_SSL_VERIFYPEER=>0,
				CURLOPT_SSL_VERIFYHOST=>0,
				CURLOPT_POSTFIELDS =>$req,
			
			); 
		    $ch = curl_init($post_url); 
		    curl_setopt_array($ch,$options); 
		   	$resultStr = curl_exec($ch);
		    curl_close($ch); 
			
			$fuioupay_log = array();
			$fuioupay_log['code'] = 'bhaController_result';
			$fuioupay_log['create_date'] = to_date(TIME_UTC,'Y-m-d H:i:s');
			$fuioupay_log['strxml'] = $resultStr;
			$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_log",$fuioupay_log);
		//}else{
		//	$resultStr = file_get_contents(APP_ROOT_PATH.'system/collocation/fuioupay/resuls.php');	
		//	$ch = 1;
		//}
			$result = array();
 			if (empty($resultStr)){
				$result = array();
				$result['resp_code'] = 9999;
				$result['pErrMsg'] = '返回出错';
				//print_r(htmlentities($result));echo "<hr/>";exit;
			}else{
				$GLOBALS['db']->query("update ".DB_PREFIX."fuioupay_cp_transaction set is_callback = 2 ,update_time=".TIME_UTC." where is_callback = 1 and requestNo = ".$requestNo);
				require_once APP_ROOT_PATH.'system/collocation/fuioupay/xml.php';
				$str3ParaInfo = @XML_unserialize($resultStr);
				$str3Req = $str3ParaInfo['ap']['plain'];
				$result = array();
				$result['resp_code'] = $str3Req["resp_code"];
				$result['mchnt_cd'] = $str3Req["mchnt_cd"];
				$result['mchnt_txn_ssn'] = $str3Req["mchnt_txn_ssn"];
				$result['signature'] =  $str3ParaInfo['ap']['signature']; 

				
				if($str3Req["resp_code"] =='0000')
				{
					if($data['mode']=='CONFIRM'){
						$sql = "update ".DB_PREFIX."fuioupay_cp_transaction set is_complete_transaction = 1,update_time=".TIME_UTC." where is_callback = 2 and requestNo = ".$requestNo;
					}elseif($data['mode']=='CANCEL'){
						//表示取消转账
						$sql = "update ".DB_PREFIX."fuioupay_cp_transaction set is_complete_transaction = 2,update_time=".TIME_UTC." where is_callback = 2 and requestNo = ".$requestNo;
					}
					
					$GLOBALS['db']->query($sql);
 					$deal_load = array();
 					if($data['mode']=='CONFIRM'){
						$deal_load['is_has_loans'] = 1;//1#转账成功
					}elseif($data['mode']=='CANCEL'){	
						$deal_load['is_repay'] = 1;//表示取消转账	
						
					}
					
				
					$where = " pP2PBillNo = ".$requestNo;

					$GLOBALS['db']->autoExecute(DB_PREFIX."deal_load",$deal_load,'UPDATE',$where);
					if($data['mode']=='CONFIRM'){
						/*modify_account(array("lock_money"=>-$t_r['money']), $t_r['user_id'],"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],招标成功",2,1);*/
						//红包状态
						if(intval($t_r['ecv_id']) > 0){
							$ecv_money = $GLOBALS['db']->getOne("select money from ".DB_PREFIX."ecv where id = ".intval($t_r['ecv_id']));
							$rs = transferBu($deal['user_id'], $mchnt_user_id, $ecv_money, $platformNo, $post_url,$deal_id,0,3,$tuser['user_name']." 使用红包:".intval($t_r['ecv_id'])." 投资[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>]");
							/*if($rs['resp_code']=="0000"){
								modify_account(array("money"=> -$ecv_money), $mchnt_user_id,$tuser['user_name']." 使用红包:".intval($t_r['ecv_id'])." 投资[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>]",3,1);
							}*/
						}
					}
					else{
						/*modify_account(array("lock_money"=>-$t_r['money'],"money"=>$t_r['money']), $t_r['user_id'],"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],流标返还",19,1);*/
						
						//释放红包
						if($t_r['ecv_id'] > 0)
						{
							$GLOBALS['db']->query("UPDATE ".DB_PREFIX."ecv SET use_count=use_count - 1 WHERE id=".$t_r['ecv_id']);
						}
						//释放加息券
						if($t_r['interestrate_id'] > 0)
						{
							$GLOBALS['db']->query("UPDATE ".DB_PREFIX."interestrate SET use_count=use_count - 1 WHERE id=".$t_r['interestrate_id']);
						}


					}
					
				}else{
					$fuiou_code = fuiou_code();
					$str =  "resp_code:".$fuiou_code[$result['resp_code']].",pErrMsg:失败";
					$error_data = array('html'=>$str);
					$GLOBALS['db']->autoExecute(DB_PREFIX."fuioupay_log",$error_data,'UPDATE',"id = ".$log_id);
				}
			
			}
		}

		require_once APP_ROOT_PATH.'app/Lib/common.php';
		require_once APP_ROOT_PATH."app/Lib/deal_func.php";
			
		$count = $GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."fuioupay_cp_transaction where code = '0000' and is_complete_transaction = 0 and tenderOrderNo = ".$deal_id);
		//print_r('xx');
		if($pTransferType ==1 && $count==0)
		{
			//print_r('bb');die;
			//已经全部放款完成,生成：还款计划以及回款计划;
			$results = do_loans($deal_id,$repay_start_time,1);
			
			if($results['status']==1){
				/*modify_account(array("money"=>$deal['borrow_amount']), $deal['user_id'],"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],招标成功",3,1);*/
			
				
				//扣除服务费
				$amt = $deal['borrow_amount']*floatval(trim($deal['services_fee'])) *0.01;
				if($amt!=0){
					$rs = transferBu($mchnt_user_id, $t_user_id, $amt, $platformNo, $post_url,$deal_id,14,"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],服务费");
					/*if($rs['resp_code']=="0000"){
						modify_account(array("money"=>-($amt)), $t_user_id,"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],服务费",14,1);
						//modify_account(array("money"=>($amt/100)), $mchnt_user_id,"[<a href='".url("index","deal#index",array("id"=>$deal['id']))."' target='_blank'>".$deal['name']."</a>],服务费",14,1);
					}*/
				}
			}
		}
		elseif($pTransferType ==2)
		{						
			$results = do_received($deal_id,1,strim($_REQUEST['status_msg']));
			//本地解冻:借款保证金,担保保证金0
			$GLOBALS['db']->query("update ".DB_PREFIX."deal set ips_over = 1 ,un_real_freezen_amt = real_freezen_amt,un_guarantor_real_freezen_amt = guarantor_real_freezen_amt where id = ".$deal_id);
			
		}
		
		if(!$t_arr){
			
			if($pTransferType ==2){
				$results['status'] = 1;
				$results['info'] = '已经批量退款过了';
				//showIpsInfo("已经批量退款过了",get_domain().APP_ROOT.'/'.URL_NAME.'?m=DealEstateOnline&a=index');
			}
			
			if($pTransferType ==1){
				$results['status'] = 1;
				$results['info'] = '已经放款过了';
				//showIpsInfo("已经批量退款过了",get_domain().APP_ROOT.'/'.URL_NAME.'?m=DealEstateOnline&a=index');
			}
		}
		
		
		return $results;
	}
	
?>